package Settings;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.HashMap;

public class Settings {
    private static Settings instance;
    private HashMap<String, String> myMap;
    private String myFileName;
    public final static String GOLDEN_IMAGE_FILENAME = "goldenImageFilename";
    public final static String DIFF_FILENAME = "diffFilename";

    private Settings(){
        myFileName = "settings.xml";
        load();
    }

    public static Settings getInstance(){
        if (instance == null){
            instance = new Settings();
        }
        return instance;
    }

    public void set(String key, String vaule){
        myMap.put(key,vaule);
    }

    public String get(String key){
        return myMap.get(key);
    }

    private void load() {
        try {
            XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(myFileName)));
            myMap = (HashMap<String, String>)decoder.readObject();
            decoder.close();
        } catch (Exception e) {
            myMap = new HashMap<String, String>();
        }

    }

    public void save() {
        if (myMap == null){
            return;
        }
        try {
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(myFileName)));
            encoder.writeObject(myMap);
            encoder.close();
        } catch (IOException e) {
            System.err.println("Settings file couldn't be saved");
        }
    }
}
